package com.alumni_circle.core.config;

import com.alumni_circle.constant.PathConstant;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 龙小虬
 * @since 2020-08-08 23:37
 */
@Component
public class TaskConfig {

    /**
     * 每天1点钟执行此方法
     * @throws IOException
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public static void deletePicture() throws IOException {
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date=sDateFormat.format(new Date());
        String path = PathConstant.SERVER.getPath();
        String deletePath = PathConstant.SERVER.getPath()+"/delete";
        File deleteFile = new File(deletePath);
        if(!deleteFile.exists()) {
            deleteFile.mkdir();
        }
        File file = new File(path);
        String[] imageName = file.list();
        for (int i = 0; i < imageName.length; i++) {
            if(sDateFormat.format(new File(path+imageName[i]).lastModified()).compareTo(date)<0 && imageName[i].contains("{-temporary}")){
                new File(path+"/"+imageName[i]).renameTo(new File(deletePath+"/"+imageName[i]));
            }
        }
        FileUtils.deleteDirectory(deleteFile);
    }
}
